﻿using System;
using System.Text.RegularExpressions;

namespace SharePoint.Orm.Helpers {
	public static class SPNameHelper {
		public static string Decode(string name) {
			name = Regex.Replace(name, "x([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])", m => {
				string str = m.Groups[1].Value;
				str = str.TrimStart('0');
				if (str.Length == 0) {
					return "";
				}
				int i = Convert.ToInt32(str, 16);
				return ((char)i).ToString();
			});
			return name;
		}

		public static string Encode(string name, bool surroundWithUnderscores) {
			name = Regex.Replace(name, "([^a-z^A-Z^0-9])", m => {
				char ch = m.Groups[1].Value[0];
				string str = "x00" + Convert.ToString(ch, 16);
				if (surroundWithUnderscores) {
					return "_" + str + "_";
				}
				return str;
			});
			return name;
		}
	}
}
